/**
 * 前端性能检测小工具（无依赖被禁用的 API）
 * 返回 { tier: 'low'|'medium'|'high', cpuScore:100, gpuScore:100 }
 */

export async function detectPerformance() {
     // ------------------------
     // 1. CPU 简易基准
     // ------------------------
     function cpuBenchmark(durationMs = 50) {
          const start = performance.now()
          let count = 0
          while (performance.now() - start < durationMs) {
               let x = 0
               for (let i = 0; i < 2000000; i++) x += Math.sqrt(i)
               count++
          }
          return count
     }

     // ------------------------
     // 3. GPU/WebGL 简易基准
     // ------------------------
     async function gpuHeavyBenchmark(size = 512, durationMs = 200) {
          return new Promise((resolve) => {
               const canvas = document.createElement('canvas')
               canvas.width = canvas.height = size
               const gl: any = canvas.getContext('webgl')
               if (!gl) return resolve(0)

               // 顶点/片元着色器
               const vertexSrc = `
               attribute vec2 pos;
               void main() { gl_Position = vec4(pos, 0.0, 1.0); }
             `
               const fragSrc = `
               precision mediump float;
               uniform float time;
               void main() {
                 vec2 uv = gl_FragCoord.xy / ${size}.0;
                 float x = uv.x;
                 for (int i = 0; i < 100; i++) {
                   x = sin(x * 1.5 + time) * cos(x + time);
                 }
                 gl_FragColor = vec4(vec3(x), 1.0);
               }
             `

               function compile(type: any, source: any) {
                    const shader = gl.createShader(type)
                    gl.shaderSource(shader, source)
                    gl.compileShader(shader)
                    return shader
               }

               const program = gl.createProgram()
               gl.attachShader(program, compile(gl.VERTEX_SHADER, vertexSrc))
               gl.attachShader(program, compile(gl.FRAGMENT_SHADER, fragSrc))
               gl.linkProgram(program)
               gl.useProgram(program)

               const buffer = gl.createBuffer()
               gl.bindBuffer(gl.ARRAY_BUFFER, buffer)
               gl.bufferData(
                    gl.ARRAY_BUFFER,
                    new Float32Array([-1, -1, 1, -1, -1, 1, 1, 1]),
                    gl.STATIC_DRAW,
               )

               const pos = gl.getAttribLocation(program, 'pos')
               gl.enableVertexAttribArray(pos)
               gl.vertexAttribPointer(pos, 2, gl.FLOAT, false, 0, 0)

               const timeLoc = gl.getUniformLocation(program, 'time')

               // 计数
               let frames = 0
               const start = performance.now()

               function render() {
                    const now = performance.now()
                    if (now - start < durationMs) {
                         gl.uniform1f(timeLoc, now / 1000)
                         gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4)
                         frames++
                         requestAnimationFrame(render)
                    } else {
                         resolve(frames)
                    }
               }
               render()
          })
     }

     // ------------------------
     // 4. 跑分
     // ------------------------
     async function cpuScoreTest() {
          let scores = []
          for (let i = 0; i < 5; i++) {
               scores.push(cpuBenchmark())
          }
          return Math.max(...scores)
     }
     async function gpuScoreTest() {
          let scores: any = []
          for (let i = 0; i < 5; i++) {
               scores.push(await gpuHeavyBenchmark())
          }
          return Math.max(...scores)
     }

     const cpuScore = await cpuScoreTest()
     const gpuScore = await gpuScoreTest()
     console.log('cpuScore', cpuScore)
     console.log('gpuScore', gpuScore)

     // ------------------------
     // 5. 分档
     // ------------------------
     let tier = 'low'
     if (cpuScore >= 15 && gpuScore >= 30) tier = 'high'
     else if (cpuScore >= 10 && gpuScore >= 24) tier = 'medium'
     console.log('finalTier', tier)

     // ------------------------
     // 6. 返回结果
     // ------------------------
     return {
          tier,
          cpuScore,
          gpuScore,
     }
}
